'use client';

import { useState, useEffect } from 'react';
import { AuthUser, LoginRequest, LoginResponse } from '@/types';

export const useAuth = () => {
  const [user, setUser] = useState<AuthUser | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // 检查本地存储中的登录状态
  useEffect(() => {
    const checkAuthStatus = () => {
      try {
        const authData = localStorage.getItem('auth');
        if (authData) {
          const parsedAuth = JSON.parse(authData);
          if (parsedAuth.isAuthenticated && parsedAuth.username) {
            setUser(parsedAuth);
          }
        }
      } catch (error) {
        console.error('Error checking auth status:', error);
        localStorage.removeItem('auth');
      } finally {
        setIsLoading(false);
      }
    };

    checkAuthStatus();
  }, []);

  // 登录函数
  const login = async (username: string, password: string): Promise<{ success: boolean; message?: string }> => {
    try {
      const response = await fetch('/api/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password }),
      });

      const result = await response.json();

      if (result.success && result.user) {
        const userData = {
          username: result.user.username,
          isAuthenticated: true,
        };
        
        setUser(userData);
        localStorage.setItem('auth', JSON.stringify(userData));
        return { success: true };
      } else {
        return { 
          success: false, 
          message: result.message || '登录失败' 
        };
      }
    } catch (error) {
      console.error('Login error:', error);
      return { 
        success: false, 
        message: '网络错误，请稍后重试' 
      };
    }
  };

  // 登出函数
  const logout = () => {
    setUser(null);
    localStorage.removeItem('auth');
  };

  // 检查是否已登录
  const isAuthenticated = user?.isAuthenticated || false;

  return {
    user,
    isLoading,
    isAuthenticated,
    login,
    logout,
  };
};
